﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;

namespace 蓝牙注册工具.BLL
{
    public class ChannelTestBLL
    {
        View.ChannelView _channelView;
        public ChannelTestBLL(View.ChannelView channelView)
        {
            _channelView = channelView;
        }

        public bool OpenPort(string portName)
        {
            try
            {
                _channelView.Dispatcher.Invoke(() => { 
                _channelView.viewModel.InitColor = Brushes.Orange;
                });
                bool isOk = BLL.PortBLL.InitPort(_channelView.serialPort, portName, 115200);
                if (isOk == false)
                {
                    _channelView.Dispatcher.Invoke(() => {
                        //_channelView.viewModel.InitColor = Brushes.OrangeRed;
                });
                return false;
                }
                _channelView.Dispatcher.Invoke(() => {
                    _channelView.viewModel.InitColor = Brushes.YellowGreen;
                });
                return true;
            }
            catch (Exception ex)
            {
                //_channelView.viewModel.InitColor = Brushes.OrangeRed;
                throw ex;
            }
        }
        bool Connect = false;
        string receive = "";
        public void Scan()
        {
            Task.Run(async() => {

                while (true)
                {
                    try
                    {
                        while (_channelView.serialPort.IsOpen == false || _channelView.serialPort.BytesToRead < 50)
                        {
                            //if (_channelView.serialPort.BytesToRead < 20)
                            //{
                            //    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "等待连接..");
                            //}
                            await Task.Delay(1000);
                        }
                        byte[] recData = new byte[_channelView.serialPort.BytesToRead];
                        _channelView.serialPort.Read(recData, 0, recData.Length);
                        string rev = Encoding.Default.GetString(recData);
                        if (rev.Contains("Version") && rev.Contains("address"))
                        {
                            Connect = true;
                            receive = rev;
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }

                }

            });

        }
        public async Task<bool> ReadInfo()
        {
            try
            {
                bool isOk = await Task.Run(async () =>
                {
                   
                    label2:
                    receive = "";
                    lock (_channelView.serialPort)
                    {
                        if (_channelView.serialPort.IsOpen)
                        {
                            _channelView.serialPort.DiscardInBuffer();
                        }
               label1:
                        if (_channelView.serialPort.IsOpen == false)
                        {
                            return false;
                        }
                        if (_channelView.serialPort.IsOpen)
                        {
                            byte[] recData = new byte[_channelView.serialPort.BytesToRead];
                            _channelView.serialPort.Read(recData, 0, recData.Length);
                            receive += Encoding.Default.GetString(recData);
                        }
                        Thread.Sleep(100);
                        //if (!receive.Contains("Software Version") || !receive.Contains("ownaddress="))
                        //{

                        //    goto label1;
                        //}
                        if (!receive.Contains("software") || !receive.Contains("ownaddress="))
                        {

                            goto label1;
                        }

                        //while (!receive.Contains("hidDevGapStateCB, 1") || !receive.Contains("start Device EVT"))
                        //{
                        //    byte[] recData = new byte[_channelView.serialPort.BytesToRead];
                        //    _channelView.serialPort.Read(recData, 0, recData.Length);
                        //    receive += Encoding.Default.GetString(recData);
                        //    Thread.Sleep(50);
                        //}
                    }
                    List<string> str = receive.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, receive);
                    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "读取设备信息");
                    //byte[] data = new byte[] { 0xA0, 0xF7, 0x01 };
                    //_channelView.serialPort.Write(data, 0, data.Length);
                    ////BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "读取设备信息");

                    //Thread.Sleep(500);
                    //string receive2 = "";                 
                    //while (_channelView.serialPort.BytesToRead > 0)
                    //{
                    //    byte[] recData = new byte[_channelView.serialPort.BytesToRead];
                    //    _channelView.serialPort.Read(recData, 0, recData.Length);
                    //    receive2 += Encoding.Default.GetString(recData);
                    //    Thread.Sleep(50);
                    //}
                    //if (receive2.Contains("start ind ad") ==false)
                    //{
                    //    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "进入模式失败");
                    //    goto label2;
                    //}
                    //BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, receive2);
                    _channelView.Dispatcher.Invoke(() =>
                    {
                        _channelView.viewModel.InfoColor = Brushes.Orange;
                        _channelView.viewModel.MacText = "蓝牙地址";
                        _channelView.viewModel.VerText = "软件版本";
                        _channelView.viewModel.SearchColor = Brushes.LightGray;
                        _channelView.viewModel.DbmText = "信号强度";
                        _channelView.viewModel.UpColor = Brushes.LightGray;

                        //string[] text = str.FindLast(it => it.Contains("Software Version"))?.Split(' ');
                        //_channelView.viewModel.VerText = text[3];

                        string[] text = str.FindLast(it => it.Contains("software"))?.Split(new char[] { '=', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        _channelView.viewModel.VerText = text[1];
                        if (str.FindLast(it => it.Contains("type=")) != null)
                        {
                            _channelView.viewModel.TypeText = text[3];
                        }
                        string[] text2 = str.FindLast(it => it.Contains("ownaddress="))?.Split(new char[] { '=', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        _channelView.viewModel.MacText = text2[6] + " " + text2[5] + " " + text2[4] + " " + text2[3] + " " + text2[2] + " " + text2[1];
                        _channelView.viewModel.InfoColor = Brushes.YellowGreen;
                    });
                    return true;
                });
                return isOk;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task<bool> dBmCheck()
        {
            try
            {
                bool isOk = await Task.Run(async () =>
                {
                    DateTime outTime = DateTime.Now.AddSeconds(30);
                    _channelView.Dispatcher.Invoke(() =>
                    {
                        _channelView.viewModel.SearchColor = Brushes.Orange;
                    });
                    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "查询信号强度...");
                    while (DateTime.Now < outTime)
                    {
                        await Task.Delay(500);
                        _channelView.serialPort.DiscardInBuffer();
                        _channelView.serialPort.DiscardOutBuffer();
                        BtLabelModel.DeviceModel device = null;
                        lock (View.BluetoothView.Macs)
                        {
                            device = View.BluetoothView.Macs.Where(it => it.Address == _channelView.viewModel.MacText).FirstOrDefault();
                        }
                        if (device == null)
                        {
                            if (DateTime.Now > outTime)
                            {
                                BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "查询超时");
                                _channelView.Dispatcher.Invoke(() =>
                                {
                                    _channelView.viewModel.SearchColor = Brushes.OrangeRed;
                                });
                                return false;
                            }
                            continue;
                        }
                        _channelView.Dispatcher.Invoke(() =>
                        {
                            _channelView.viewModel.DbmText = device.DBm.ToString() + "dBm";
                        });
                        BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, device.DBm.ToString() + "dBm");
                            if (device.DBm < int.Parse(MainWindow.config.dBm))
                            {
                                _channelView.Dispatcher.Invoke(() =>
                                {
                                    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, _channelView.viewModel.DbmText);
                                    _channelView.viewModel.SearchColor = Brushes.OrangeRed;
                                });
                                return false;
                            }
                        //await Task.Delay(1000);
                        _channelView.Dispatcher.Invoke(() =>
                        {
                            _channelView.viewModel.SearchColor = Brushes.YellowGreen;
                        });
                        return true;
                    }
                    _channelView.Dispatcher.Invoke(() =>
                    {
                        BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.OrangeRed, "超时");
                        _channelView.viewModel.SearchColor = Brushes.OrangeRed;
                    });
                    return false;
                });
                return isOk;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static object loc = new object();
        public async Task<bool> SignUp()
        {
            try
            {
                _channelView.Dispatcher.Invoke(() => { 
                _channelView.viewModel.UpColor = Brushes.Orange;
            });
            string responseContent="";
                await Task.Run(() =>
                {
                    lock (loc)
                    {
                        BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, "注册设备");
                        BtLabelModel.HttpModel.SignUpDto dto = new BtLabelModel.HttpModel.SignUpDto
                        {
                            mac = _channelView.viewModel.MacText,
                            version = _channelView.viewModel.VerText,
                            type = _channelView.viewModel.TypeText,
                            rssi = int.Parse(_channelView.viewModel.DbmText.Replace("dBm","")),
                            ts = BtLabelTool.CommonHelper.GetTimeStamp()
                        };
                        string key = "GIzs4q1sD9Wg83u6G60NDJcMmgnUcwKN";
                        string jsonStr = JsonConvert.SerializeObject(dto);
                        MD5 md5 = MD5.Create(); //实例化一个md5对像
                        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(jsonStr + dto.ts + key));
                        string poststr = BitConverter.ToString(s).Replace("-", "").ToLower();
                        responseContent = BtLabelDAL.HttpDAL.HttpPost(MainWindow.config.SignupUrl + $"ts={dto.ts}&sign={poststr}", JsonConvert.SerializeObject(dto));
                    }
                    BtLabelBLL.UiBLL.RichTextBoxAppendText(_channelView.RichTextBoxLog, Brushes.Blue, responseContent);
                });
                if (!responseContent.Contains("\"code\":200"))
                {
                    _channelView.Dispatcher.Invoke(() => { 
                    _channelView.viewModel.UpColor = Brushes.OrangeRed;
                });
                return false;
                }
                _channelView.Dispatcher.Invoke(() => { 
                _channelView.viewModel.UpColor = Brushes.YellowGreen;
                });
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
